package com.acme.service.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.domain.bank.Bank;
import com.acme.exceptions.ConnectionLostException;
import com.acme.exceptions.ServerAlreadyRunningException;

public class BankServer {
	private static ServerSocket providerSocket;
	private static Socket connection = null;
	
	
	public static void startServer(Bank bank) throws ServerAlreadyRunningException, ConnectionLostException {
		try {
			providerSocket = new ServerSocket(2013);
		} catch (IOException e) {
			throw new ServerAlreadyRunningException("Another instance of server " +
					"is already running");
		}
		String messageFromClient = null;
		String messageToClient;
		do {
			try {
				System.out.println("Waiting for connection...");
				connection = providerSocket.accept();
				System.out.println("Connection established");
				ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
				ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
				while(true) {
					try {
						messageFromClient = (String)ois.readObject();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					if ( "exit".equals(messageFromClient) || "halt".equals(messageFromClient)){
						messageToClient = BankReport.exitMessage();
						break;
					} else if ( "bankinfo".equals(messageFromClient)) {
						messageToClient = BankReport.bankInfoMessage(bank);
					} else {
						messageToClient = BankReport.wrongCommandMessage();
					}
					oos.writeObject(messageToClient);
				}
				oos.close();
				ois.close();
				connection.close();
				System.out.println("Lost connection with client");
			} catch(IOException e){
				throw new ConnectionLostException("Lost connection with client");
			}
		} while (!"halt".equals(messageFromClient) );
		try {
			providerSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
